package com.example.demo.controller;

import com.example.demo.model.Major;
import com.example.demo.service.MajorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/majors")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class MajorController {
    @Autowired
private MajorService majorService;

    // 获取所有专业（支持分页和搜索）
    @GetMapping
    public Page<Major> getAllMajors(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String status) {
        
        // 如果提供了搜索条件，则执行搜索
        if ((name != null && !name.isEmpty()) || (status != null && !status.isEmpty())) {
            Major.Status statusEnum = null;
            if (status != null && !status.isEmpty()) {
                try {
                    statusEnum = Major.Status.valueOf(status);
                } catch (IllegalArgumentException e) {
                    // 如果状态值无效，则忽略状态搜索条件
                }
            }
            return majorService.searchMajors(name, statusEnum, page, size);
        } else {
            // 否则返回所有专业
            return majorService.getAllMajors(page, size);
        }
    }

    // 根据ID获取专业
    @GetMapping("/{id}")
    public ResponseEntity<Major> getMajorById(@PathVariable Long id) {
        Optional<Major> major = majorService.getMajorById(id);
        if (major.isPresent()) {
            return ResponseEntity.ok(major.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建专业
    @PostMapping
    public Major createMajor(@RequestBody Major major) {
        return majorService.saveMajor(major);
    }

    // 更新专业
    @PutMapping("/{id}")
    public ResponseEntity<Major> updateMajor(@PathVariable Long id, @RequestBody Major majorDetails) {
        Optional<Major> major = majorService.getMajorById(id);
        if (major.isPresent()) {
            Major updatedMajor = major.get();
            updatedMajor.setName(majorDetails.getName());
            updatedMajor.setCode(majorDetails.getCode());
            updatedMajor.setCollegeId(majorDetails.getCollegeId());
            updatedMajor.setDescription(majorDetails.getDescription());
            updatedMajor.setStatus(majorDetails.getStatus());
            majorService.saveMajor(updatedMajor);
            return ResponseEntity.ok(updatedMajor);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除专业
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteMajor(@PathVariable Long id) {
        Optional<Major> major = majorService.getMajorById(id);
        if (major.isPresent()) {
            // 检查专业是否有关联的班级
            if (majorService.hasClasses(id)) {
                return ResponseEntity.badRequest().body("无法删除专业，该专业下有关联的班级数据");
            }
            
            majorService.deleteMajor(id);
            return ResponseEntity.ok("专业删除成功");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据代码和学院ID获取专业
    @GetMapping("/code/{code}/college/{collegeId}")
    public ResponseEntity<Major> getMajorByCodeAndCollegeId(@PathVariable String code, @PathVariable Long collegeId) {
        Optional<Major> major = majorService.getMajorByCodeAndCollegeId(code, collegeId);
        if (major.isPresent()) {
            return ResponseEntity.ok(major.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据名称搜索专业
    @GetMapping("/search")
    public List<Major> searchMajorsByName(@RequestParam String name) {
        return majorService.getMajorsByName(name);
    }

    // 根据学院ID获取专业
    @GetMapping("/college/{collegeId}")
    public List<Major> getMajorsByCollegeId(@PathVariable Long collegeId) {
        return majorService.getMajorsByCollegeId(collegeId);
    }
}